package session;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

/**
 * @author 石小俊
 * @date 2023年07月04日 14:04
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if("/show.code".equals(path)){
            showCode(request,response);
        }
        if("/login.code".equals(path)){
            login(request,response);
        }
        if("/register.code".equals(path)){
            register(request,response);
        }
        if("/logout.code".equals(path)){
            logout(request,response);
        }
        if("/logout2.code".equals(path)){
            logout2(request,response);
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 方法一:直接移除session的user信息
        request.getSession().removeAttribute("user");
        response.sendRedirect(request.getContextPath()+"/session/main.jsp");
    }

    protected void logout2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 方法二:直接清除原有的session
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/session/main.jsp");
    }

    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");

            // 判断用户名是否重复
            // 可以先根据当前用户名查询对应的用户信息
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            rs = ps.executeQuery();
            if(rs.next()){
                request.setAttribute("registerMsg","该用户已经被注册");
                request.getRequestDispatcher("/session/register.jsp").forward(request,response);
                return;
            }
            // 如果用户名尚未注册,则执行注册业务
            sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,phone);
            ps.setString(4,address);
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/session/login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/session/register.jsp").forward(request,response);
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected void showCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        // 在内存中定义一个画板
        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);
        // 获取画板中对应的画笔
        Graphics graphics = image.getGraphics();
        // 指定画笔所填充的矩形区域
        graphics.fillRect(0,0,50,25);
        // 设置画笔的颜色,设置一个随机色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
        // 设置画笔对应的字体样式
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));
        // 验证码内容,要求:随机数字或者英文字母
        String s = "0123456789qwertyuioplkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        // 生成验证码之后需要与用户输入的验证码进行校验
        // 为了便于读取图片中的验证码内容
        // 在此处可以将验证码存放到session中
        request.getSession().setAttribute("code",buffer.toString());
        System.out.println("验证码:"+buffer);

        // 将随机生成的字符绘制到图片中
        graphics.drawString(buffer.toString(),5,18);
        // 输出图片
        ImageIO.write(image,"JPEG",response.getOutputStream());

    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求中的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        // 获取验证码图片中的内容
        String image = (String) request.getSession().getAttribute("code");

        // 校验验证码
        if(!code.equals(image)){
            request.setAttribute("loginMsg","验证码不正确");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
            return;
        }

        // 校验用户名与密码是否正确
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                // 当用户成功登录之后,将查询出来的用户信息保存到session中
                request.getSession().setAttribute("user",user);
                response.sendRedirect(request.getContextPath()+"/session/main.jsp");
                return;
            }
            request.setAttribute("loginMsg","用户名或密码错误");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
